Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

1.3K
Visualizações
Trying to pass variable from JavaScript to PHP using Ajax but got error " Undefined array key"

I have had this error for multiple days now, I have tried searching this error up but whenever I search this error up it gives a different reason for the error and when I try to add what other sites say it doesn't work which is why I am asking here as I don't see what else I can do.

I am trying to pass a variable from JavaScript to PHP but it is not working and I have no idea why.

Here is my JavaScript code:

<head>
<script type="text/javascript" src="jquery.js"> </script>
</head>

<script>
var variable = "hello";
console.log(variable);
$.ajax
    ({
        url: "ajax.php",
        type: "POST",
        data:{pass : variable},
        success: function() { 
              alert("Success"); 
        } 
    });

</script>

Here is my PHP code:

$variable = $_POST['pass'];
echo($variable);

Everything seems to work perfectly. It writes the variable to the console, it comes up with the alert saying success. However I get an error message saying: 'Undefined array key "pass"'

What is causing this? Thank you?

Edit: People have told me to use isset, I have added that it removed the error however it still does not echo the PHP variable, meaning it is still not been passed to PHP, I am still trying to find how to fix this.

over 4 years ago · Santiago Trujillo
3 Respostas
Responde à pergunta

0

Your front end code looks OK, but I don't know your target PHP environement, but maybe your environnement doesn't accept formData.

By default, jQuery send ajax POST data as formData.

Try to send data as JSON

$.ajax({
    url: "ajax.php",
    type: "POST",
    data: JSON.stringify({pass : variable}),
    dataType: "json",
    contentType: "application/json; charset=utf-8",
    success: function(data){alert(data);},
});

And then you will probably have to adapt your php code:

$json = file_get_contents('php://input');
// Converts it into a PHP array
$data = json_decode($json, true);
$variable = $data['pass'];
echo($variable);
over 4 years ago · Santiago Trujillo Relatório

0

Can you please use the developer tools in chrome browser that will help you to find if data is properly sent to php file. Also you can try $_REQUEST instead of post just to check what data is coming in REQUEST as it works for GET & POST both. If it still does not help you.

Also can you please use

data: {'pass':variable}

instead of

data: {pass:variable}

let me know if it works for you.

over 4 years ago · Santiago Trujillo Relatório

0

If you get this error in your ajax.php file which you Post the data to it, I say it's normal because when you open that file (ajax.php) it's like that there is no $_POST['pass'] because you just opened that file without running JS to send data. If you want to receive data that you send you can do this:

Your JS code I call this file index:

var variable = "hello";
$.ajax
({
    url: "ajax.php",
    type: "POST",
    data:{pass : variable},
    success: function(res) { 
          alert(res); 
    } 
});

The PHP file:

$variable = $_POST['pass'];
echo($variable);

Then if You open up that index file, after running the JS code it'll send that post data to your PHP file and your PHP file will echo that, then the value will store in that res variable which when every thing went fine, you can see the alert of that res in the page (index file).

Notice that as I said you can't open up the PHP file lonely because it doesn't receive a post data on its own, it is normal for undefined to return.

over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda